<?php

namespace App\Http\Controllers;

use App\Http\Model\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class IndexController extends Controller
{
    public function index(){//后台首页显示方法
        $admin = session('admin');//获取缓存账号session
        return view('home.index')->with('admin',$admin);//把数据返回页面
    }

    public function info(){
        $admin = session('admin');//获取缓存账号session
        return view('home.info')->with('admin',$admin);
    }

    public function pass(){//修改密码方法

        if($input = Input::all()){//判断是否有数据传过来
            $rules = [
                'password_o' => 'required',
                'password' => 'required|between:6,20|confirmed',
            ];

            $message = [
                'password_o.required' => '原密码不能为空',
                'password.required' => '新密码不能为空',
                'password.between' => '新密码必须在6-20位之间',
                'password.confirmed' => '新密码和确认密码不一致',
            ];
            $validator = Validator::make($input,$rules,$message);//laravel的验证机制
            if($validator->passes()){//验证信息是否符合要求
                $admin = session('admin');
                $_password = Crypt::decrypt($admin->password);//解密密码
                if($input['password_o']==$_password){//判断原密码是否正确
                    $password= Crypt::encrypt($input['password']);
                    $res= DB::table('admin')->where('id','=',$admin['id'])->update(['password'=>$password]);//修改表数据
                    if($res){
                        $errors = ['密码修改成功'];
                        return back()->with('errors',$errors);
                    }
                }else{
                    $errors = ['原密码错误'];
                    return back()->with('errors',$errors);
                }
            }else{
                return back()->withErrors($validator);//返回错误信息到页面
            }
        }else{
            return view('home.pass');
        }
    }
}
